package com.wld.blacklist.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wld.blacklist.common.enums.CodeEnum;
import com.wld.blacklist.common.mapstruct.ClassCopy;
import com.wld.blacklist.dao.entity.Article;
import com.wld.blacklist.dao.entity.Comment;
import com.wld.blacklist.dao.model.QueryDetailsInVo;
import com.wld.blacklist.dao.model.SaveCommentInVo;
import com.wld.blacklist.dao.result.ResultVo;
import com.wld.blacklist.service.ArticleService;
import com.wld.blacklist.service.DetailsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

/**
 * 文章详情
 * @author ludiWang
 * @version 1.0.0
 * @date 2022年3月3日 16:20:10
 */
@Slf4j
@Controller
@Validated
@RequestMapping("/details")
public class DetailsController {
    private DetailsService detailsService;
    private ArticleService articleService;
    private ClassCopy classCopy;
    @Autowired
    public DetailsController(DetailsService detailsService,ArticleService articleService,ClassCopy classCopy) {
       this.detailsService = detailsService;
       this.articleService = articleService;
       this.classCopy = classCopy;
    }

    @ResponseBody
    @RequestMapping("/id")
    public ResultVo query(@RequestBody @Validated QueryDetailsInVo queryDetailsInVo){
        log.info("Into DetailsController.query(),params：{}",queryDetailsInVo);
        try {
            List<Comment> queryList = detailsService.query(queryDetailsInVo.getArticleId());
            QueryWrapper<Article> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("id",queryDetailsInVo.getArticleId());
            Article article = articleService.getOne(queryWrapper);

            return ResultVo.success(CodeEnum.SUCCESS,queryList,article);
        }catch (Exception e){
            log.error("查看文章详情错误：",e);
            return ResultVo.failed(CodeEnum.SYS_ERROR);
        }
    }

    @ResponseBody
    @RequestMapping("/save")
    @Transactional(rollbackFor = Exception.class)
    public ResultVo save(@RequestBody @Validated SaveCommentInVo saveCommentInVo){
        log.info("Into DetailsController.save(),params：{}",saveCommentInVo);
        try {
            Comment comment = classCopy.commentInVoToComment(saveCommentInVo);
            detailsService.save(comment);
            return ResultVo.success();
        }catch (Exception ex){
            log.error("添加评论错误：",ex);
            return ResultVo.failed(CodeEnum.SYS_ERROR);
        }
    }

}
